package interceptor;

import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.ActionInvocation;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.ArrayList;

import utils.DBVar;
import utils.DBConnection;
import utils.Var;

public class ConnectionInterceptor implements Interceptor {

  public void init() {
  }

  public void destroy() {
  }

  public String intercept(ActionInvocation actionInvocation) throws Exception {
    Class actionClass = actionInvocation.getAction().getClass();
    ArrayList<Connection> autoCommitOns = new ArrayList<Connection>();
    ArrayList<Connection> autoCommitOffs = new ArrayList<Connection>();

    Method[] methods = actionClass.getMethods();
    for (Method method : methods) {
      InjectConnection ic = method.getAnnotation(InjectConnection.class);
      if (ic == null) continue;
      String tableName = ic.tableName().length() == 0 ? DBVar.TABLENAME : ic.tableName();
      Connection con = new DBConnection(tableName, ic.autoCommit()).getConnection(ic.encoding());
      method.invoke(actionInvocation.getAction(), con);
      if (ic.autoCommit()) autoCommitOns.add(con);
      else autoCommitOffs.add(con);
    }

    String result = actionInvocation.invoke();
    for (Connection con : autoCommitOffs) {
      if (result.equals(Var.ACTION_ERROR)) con.rollback();
      else con.commit();
    }

    for (Connection con : autoCommitOns) con.close();
    for (Connection con : autoCommitOffs) con.close();

    return result;
  }
}
